/**
 * 自动翻页和size改变自动切换的table
 */
import React, { Component } from 'react';
import { Table } from 'antd';
import _ from 'lodash';
import getPagination from './pagination';
import { isSuccess } from '../configs/error';
import { randomKey } from './filter';

class MyTable extends Component {
	state = {
		dataSource: [],
		current: 1,
		size: 10,
		total: 0,
		display: []
	}

	componentWillMount() {
		this.query();
		this.getPagination();
	}

	componentWillReceiveProps(nextProps) {
		if (!_.isEqual(nextProps.queryData, this.props.queryData)) {
			this.setState({ current: 1 });
		}
	}

	componentWillUpdate(nextProps, nextState) {
		this.getPagination(nextState);
	}

	componentDidUpdate(prevProps, prevState) {
		const { current, size } = this.state;
		const { queryData } = this.props;
		if (!_.isEqual(prevProps.queryData, queryData) || current !== prevState.current || size !== prevState.size) {
			setTimeout(() => {
				this.query();
			}, 0);
		}
	}

	getPagination(state) {
		const { current, total } = state || this.state;
		this.pagination = getPagination({
			current,
			total,
			onChange: this.pageChange,
			onShowSizeChange: this.pagesizgeChange
		});
	}

	defaultState = { ...this.state }

	merge() {
		const { current, size } = this.state;
		const { queryData } = this.props;
		return { ...queryData, current, size };
	}

	async query() {
		const { dataChange } = this.props;
		const data = this.merge();
		delete data[randomKey];
		if (data.query && data.query[randomKey]) {
			delete data.query[randomKey];
		}
		const res = await this.queryData(data);
		if (isSuccess(res)) {
			const { total, records } = res.data;
			this.setState({
				total,
				dataSource: records,
				display: res.display
			});
			if (typeof dataChange === 'function')dataChange(res.data);
		}
	}

	queryData(data) {
		const { query } = this.props;
		if (typeof query === 'function') return query(data);
		// 请求数据，需继承实现
	}

	pageChange = current => {
		this.setState({ current });
	}

	pagesizgeChange = (current, size) => {
		this.setState({ size, current: 1 });
	}

	render() {
		const { notShow = [], columns, ...props } = this.props;
		const { dataSource } = this.state;
		return (
			<Table
				dataSource={dataSource}
				columns={(this.columns || columns).filter(c => !notShow.includes(c.key))}
				pagination={this.pagination}
				{...props}
			/>
		);
	}
}

export default MyTable;
